<?php 

namespace controller;

require_once("pageView.php");
require_once('HTMLmodel.php');

class loginController{

	private static $username = "Admin";
	private $password;
	private $HTMLmodel; 
	private $pageView;


	/**
	 * Check state of site and run appropriate method to output html
	 */
	public function __construct(){
        session_start();                
        $this->HTMLmodel = new \model\HTMLmodel();
        $this->pageView = new \view\pageView();  
        $this->password = md5("Password");  	

        if (isset($_GET['logout']) && isset($_SESSION['username'])) {
            $this->doLogout();              
        }
        else if (isset($_SESSION['username']) && isset($_SESSION['password'])) {
            $this->validateSession();
        }
        else if (isset($_COOKIE['Username']) && isset($_COOKIE['Password'])) {          	
        	$this->validateCookie();
        }
        else if (isset($_POST['username']) && isset($_POST['password'])) {
            $postUser = $_POST['username'];
            $postPass = md5($_POST['password']);

            $this->validateLogin($postUser, $postPass);
        }
        else{ $this->getStartPage(); }           
    }

    /**
     * @param String $postUser
     * @param String $postPass
     * @return void
     */
	private function CreateLoginCookie($postUser, $postPass) {
		$cookieDeath = time() + 30;
		file_put_contents("cookieDeath.txt", $cookieDeath);
		setcookie("Username", $postUser, $cookieDeath);
		setcookie("Password", $postPass, $cookieDeath);
	}

	/**
	 * @param String $postUser Posted username
	 * @param String $postPass Posted password
	 * @return void
	 */	
	private function validateLogin($postUser, $postPass) {
	    if (!empty($_COOKIE['Password']) && $postPass != $this->password) {	 	    	
	    		$this->doCookieError($postUser, $postPass);	    	
	    }
	    else if (empty($postUser)) {
            $error = "Användarnamn saknas";
            $this->pageView->getHTMLpage("Ej inloggad", 
            $this->HTMLmodel->getErrorPage($error, $postUser));                     
	    }
	    else if (empty($postPass)) {
            $error = "Lösenord saknas";
            $this->pageView->getHTMLpage("Ej inloggad", 
            $this->HTMLmodel->getErrorPage($error, $postUser));             
	    }
	    else if (!$this->validatePassword($postPass) || 
	        !$this->validateUsername($postUser)) {
	        $error = "Felaktig användarnamn eller lösenord";
	        $this->pageView->getHTMLpage("Ej inloggad", 
	        $this->HTMLmodel->getErrorPage($error, $postUser));                     
	    }
	    else {
	        $this->doLogin($postUser, $postPass, "Inloggning lyckades");	        
	    }                              
    }

    /**
     * Check wether cookie is valid or not
     * @return bool
     */
    private function validateCookie() {
    	$cookieDeathTime = file_get_contents("cookieDeath.txt");
    	if (time() > $cookieDeathTime) {
    		$this->doCookieError();
    	}
    	else {
    		$this->validateLogin($_COOKIE['Username'], $_COOKIE['Password']);	
    	}
    }

    private function validateSession() {
    	if ($_SERVER['HTTP_USER_AGENT'] != $_SESSION['sessionUser']) {
			$this->getStartPage();
    	}
    	else {
			$username = $_SESSION['username'];
	        $this->sessionLogin($username);
    	}
    }

	/**
	 * @return void
	 */
	private function doLogout() {
		$this->pageView->getHTMLpage("Ej inloggad", 
		$this->HTMLmodel->getLoggedOutPage());

		setcookie("Username", "", time()-3600);
		setcookie("Password", "", time()-3600);

		$_SESSION = array();
    	session_destroy();
	}

	/**
	 * @return void
	 */
	private function doCookieError() {
		$error = "Felaktig information i cookie";
	    $this->pageView->getHTMLpage("Ej inloggad", 
	    $this->HTMLmodel->getErrorPage($error, ""));  

	    setcookie("Username", "", time()-3600);
		setcookie("Password", "", time()-3600);
	    
		$_SESSION = array();
    	session_destroy();
	}

	/**
	 * @param  String $postUser 
	 * @param  String $postPass 
	 * @param  String $message 
	 * @return void
	 */
	private function doLogin($postUser, $postPass, $message) {
		$_SESSION['username'] = $postUser;
	    $_SESSION['password'] = $postPass;
	    $_SESSION['sessionUser'] = $_SERVER["HTTP_USER_AGENT"];
	    if (isset($_POST['remember'])) {
	    	$this->CreateLoginCookie($postUser, $postPass);
	    	$this->pageView->getHTMLpage($postUser." är inloggad", 
	    	$this->HTMLmodel->getLoggedInPage
	    	("Inloggning lyckades och vi kommer ihåg dig nästa gång"));    
	    }
	    else if (isset($_COOKIE['Username']) && isset($_COOKIE['Password'])) {
	    	$this->pageView->getHTMLpage($postUser." är inloggad", 
	    	$this->HTMLmodel->getLoggedInPage
	    	("Inloggning lyckades via cookies"));    
	    }
	    else{
	    	$this->pageView->getHTMLpage($postUser." är inloggad", 
	    	$this->HTMLmodel->getLoggedInPage($message));   	
	    }
	}

	/**
	 * @return void
	 */
	public function getStartPage() {
		$pageView = new \view\pageView();
		$HTMLmodel = new \model\HTMLmodel();
		$pageView->getHTMLpage("Ej inloggad", $HTMLmodel->getStartPage());
	}

	/**
	 * @param String $postPass
	 * @return void
	 */
	private function sessionLogin($postPass) {

		$this->pageView->getHTMLpage($postPass." är inloggad", 
		$this->HTMLmodel->getSessionLoginPage());
	}

	/**
	 * @param $username
	 * @param $password
	 * @return bool
	 */
	private function validateUsername($postUsername) {
		if ($postUsername == self::$username) {
			return true;
		}
	}

	/**
	 * @param $username
	 * @param $password
	 * @return bool
	 */
	private function validatePassword($postPassword) {
		if ($postPassword == $this->password) {
			return true;
		}
	}
}